package RPC;

import Constant.constant;
import com.rabbitmq.client.*;
import jdk.swing.interop.SwingInterOpUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建链接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //2.设置参数
        factory.setHost(constant.localhost);
        factory.setPort(constant.port);
        factory.setVirtualHost(constant.VirtuHost);
        factory.setUsername(constant.UserName);
        factory.setPassword(constant.Password);
        //3.创立链接
        Connection connection=factory.newConnection();
        //4.创建channel信道
        Channel channel=connection.createChannel();
        //接受请求
//        1 表示消费者每次从 RabbitMQ 服务器最多预取 1 条消息
//        在处理完当前消息并确认之前，不会接收新的消息
        channel.basicQos(1);
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
               String request=new String(body,"UTF-8");
                System.out.println("接收到请求:"+request);
                String response="针对request"+request+",响应成功";
                AMQP.BasicProperties basicProperties=new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("",constant.RPC_RESPONSE_QUEUE,basicProperties,response.getBytes(StandardCharsets.UTF_8));
                //不进行批量处理 比如deliverytag=2 则只处理2 不处理2及以前的
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //不自动确认
        channel.basicConsume(constant.RPC_REQUEST_QUEUE,false,consumer);

    }
}
